<template>
  <div class="manage">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="碳交易" name="first">
        <!-- 碳交易列表 -->
        <el-table
          :data="tradeData"
          style="width: 100%">
          <el-table-column
            prop="id"
            label="序号"
            min-width="100"
          >
            <template slot-scope="scope">
              {{ scope.$index + 1 + (form.pageNum - 1) * form.pageSize }}
            </template>
          </el-table-column>
          <el-table-column
            prop="date"
            label="日期"
            min-width="150">
          </el-table-column>
          <el-table-column
            prop="price"
            label="价格(USD)"
            min-width="160">
          </el-table-column>
          <el-table-column
            prop="area"
            label="市场"
            min-width="120">
          </el-table-column>
          <el-table-column
            label="操作"
            max-width="140">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="showBuy(scope.row, tradeData)"
                type="primary"
                size="small">
                买入
              </el-button>
              <el-button
                @click.native.prevent="showSell(scope.row, tradeData)"
                type="warning"
                size="small">
                卖出
              </el-button>
            </template>
          </el-table-column>
        </el-table>


      </el-tab-pane>
      <el-tab-pane label="交易记录" name="second">
        <div style="margin: 10px">
          <el-select v-model="form.tradeType" placeholder="请选择交易类型" clearable>
            <el-option
              v-for="(item,index) in [{status:0,name:'卖出'},{status:1,name:'买入'},{status:2,name:'政府免费发放'}]"
              :label="item.name"
              :value="item.status"></el-option>
          </el-select>
          <el-select style="margin-left: 10px" v-model="form.assertType" placeholder="请选择碳资产类型" clearable>
            <el-option
              v-for="(item,index) in [{status:0,name:'配额'},{status:1,name:'CCER'}]"
              :label="item.name"
              :value="item.status"></el-option>
          </el-select>
          <el-button class="filter-item" type="danger" icon="el-icon-search" @click="searchTarget"
                     style="margin-bottom: 5px;margin-left: 10px"
          >
            查找
          </el-button>

          <el-button class="filter-item" type="" icon="el-icon-refresh" @click="clean"
                     style="margin-bottom: 5px;margin-left: 10px"
          >
            重置
          </el-button>
        </div>
        <el-table
          :data="tableData"
          style="width: 100%">
          <el-table-column
            prop="id"
            label="序号"
            min-width="40"
          >
            <template slot-scope="scope">
              {{ scope.$index + 1 + (form.pageNum - 1) * form.pageSize }}
            </template>
          </el-table-column>
          <el-table-column
            prop="tradeType"
            label="交易类型"
            min-width="150">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.tradeType === 0" type="success" style="font-family: 微软雅黑,serif">
                卖出
              </el-tag>
              <el-tag v-if="scope.row.tradeType === 1" type="warning" style="font-family: 微软雅黑,serif">
                买入
              </el-tag>
              <el-tag v-if="scope.row.tradeType === 2" type="normal" style="font-family: 微软雅黑,serif">
                政府免费发放
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="tradeType"
            label="碳资产类型"
            min-width="150">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.quotaType === 0" type="info" style="font-family: 微软雅黑,serif">
                碳配额
              </el-tag>
              <el-tag v-if="scope.row.quotaType === 1" type="warning" style="font-family: 微软雅黑,serif">
                CCER
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="tradeQuantity"
            label="交易数量"
            min-width="120">
            <template slot-scope="scope">
              <el-tag type="info" style="font-family: 微软雅黑,serif">
                {{ scope.row.tradeQuantity }} tCO2
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="tradePrice"
            label="交易价格"
            min-width="80">
          </el-table-column>
          <el-table-column
            prop="area"
            label="交易市场"
            min-width="80">
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="交易时间"
            max-width="180">
          </el-table-column>
        </el-table>
        <!--  分页  -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="form.pageNum"
          :page-sizes="[5, 10, 20, 30, 40, 50]"
          :page-size="form.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="碳资产使用" name="third">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>碳配额</span>
              </div>
              <div>当前可用碳配额：{{ tradeInfo.ableQuota.toFixed(2) }}</div>
              <hr>
              <div>当前已使用碳配额：{{ tradeInfo.usedQuota.toFixed(2) }}</div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>CCER</span>
              </div>
              <div>当前可用CCER：{{ tradeInfo.ableCcer.toFixed(2) }}</div>
              <hr>
              <div>当前已使用CCER：{{ tradeInfo.usedCcer.toFixed(2) }}</div>
            </el-card>
          </el-col>
        </el-row>
        <br>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>碳配额使用</span>
              </div>
              <el-input-number v-model="quotaNum" style="width: 500px;" :precision="2" :step="0.01"
                               :max="tradeInfo.ableQuota" :min="0.00"></el-input-number>
              <el-button style="float: right" type="primary" @click="assertTrade(1)">确认</el-button>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>CCER使用</span>
              </div>
              <el-input-number v-model="ccerNum" style="width: 500px;" :precision="2" :step="0.01"
                               :max="tradeInfo.ableCcer" :min="0.00"></el-input-number>
              <el-button style="float: right" type="primary" @click="assertTrade(2)">确认</el-button>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>


    <el-dialog title="碳买入" :visible.sync="dialogFormVisible" width="70%">
      <el-form ref="form" :model="tradeForm" label-width="80px">
        <el-form-item label="单价">
          <el-input disabled v-model="tradeForm.price"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="tradeForm.type" placeholder="请选择购入类型">
            <el-option label="碳配额" value="quota"></el-option>
            <el-option label="CCER" value="ccer"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="购入量">
          <el-input-number v-model="tradeForm.num" style="width: 500px;" :precision="2" :step="0.01"
                           @change="changeQuantity"
                           :min="0.00"></el-input-number>
        </el-form-item>
        <el-form-item label="总金额">
          <el-input type="input" disabled v-model="tradeForm.totalPrice"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmBuy">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="碳资产卖出" :visible.sync="dialogFormVisible1" width="70%">
      <el-form ref="form" :model="tradeForm" label-width="80px">
        <el-form-item label="单价">
          <el-input disabled v-model="tradeForm.price"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="tradeForm.type" placeholder="请选择卖出类型">
            <el-option label="碳配额" value="quota"></el-option>
            <el-option label="CCER" value="ccer"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="购入量">
          <el-input-number v-model="tradeForm.num" style="width: 500px;" :precision="2" :step="0.01"
                           @change="changeQuantity"
                           :min="0.00"></el-input-number>
        </el-form-item>
        <el-form-item label="总金额">
          <el-input type="input" disabled v-model="tradeForm.totalPrice"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="confirmSell">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import {editTarget, enableTarget, unEnableTarget} from "@/api/carbon-manage/target";
import {listStage} from "@/api/carbon-manage/data";
import {queryAllProcess} from "@/api/carbon-manage/process";
import {
  buyCarbon,
  carbonAssertTrade,
  queryCarbonAssert,
  queryNewPrice,
  queryTradeList, sellCarbon
} from "@/api/carbon-manage/trade";
import {hideFullScreenLoading, showFullScreenLoading} from "@/utils/loading";

export default {
  data() {
    return {
      tradeData: [],
      activeName: 'first',
      tradeInfo: {},
      quotaNum: 0.00,
      ccerNum: 0.00,
      activities: [{
        content: '开始日期',
        timestamp: '2018-04-12 20:46',
        size: 'large',
        type: 'primary',
        color: '#c2e0c9'
      }, {
        content: '结束日期',
        timestamp: '2018-04-03 20:46',
        color: '#fa8888'
      }],
      detail: {
        id: -1,
        name: '',
        beginDate: '',
        endDate: '',
        enable: false,
        stageList: [],
        processList: [],
        targetAmount: 0,
        remark: '',
        percentage: 0,
      },
      percentage: 90,
      customColor: '#409eff',
      customColors: [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 40},
        {color: '#5cb87a', percentage: 60},
        {color: '#1989fa', percentage: 80},
        {color: '#6f7ad3', percentage: 100}
      ],
      dialogFormVisible: false,
      dialogFormVisible1: false,
      editTargetVisible: false,
      formLabelWidth: '90px',
      total: 0,
      form: {
        pageNum: 1,
        pageSize: 10,
        tradeType: '',
        assertType: '',
      },
      assertDto: {
        type: -1,
        num: 0
      },
      tradeForm: {
        price: 0,
        totalPrice: 0,
        num: 0,
        type: null,
        area: ""
      },
      tableData: [],
      ruleForm: {
        id: -1,
        name: '',
        beginDate: '',
        endDate: '',
        enable: false,
        stageList: [],
        processList: [],
        targetAmount: 0,
        remark: '',
        warningPercent: 0,
      },
      stages: [],
      processes: [],
      dateRange: [],
      rules: {
        name: [
          {required: true, message: '请输入活动名称', trigger: 'blur'},
        ],
        processList: [
          {type: 'array', required: true, message: '请至少选择一个工序', trigger: 'change'}
        ],
        beginDate: [
          {type: 'date', required: true, message: '请选择开始日期', trigger: 'change'}
        ],
        endDate: [
          {type: 'date', required: true, message: '请选择结束日期', trigger: 'change'}
        ],
        stageList: [
          {type: 'array', required: true, message: '请至少选择一个生产阶段', trigger: 'change'}
        ],
        targetAmount: [
          {required: true, message: '请输入目标碳排放', trigger: 'change'}
        ]
      },
      selectTrade: {},

    }
  },
  mounted() {
    showFullScreenLoading()
    this.loadData();
    listStage().then(res => {
      this.stages = res.data;
    });
    queryAllProcess().then(res => {
      this.processes = res.data;
    });

    queryCarbonAssert().then(res => {
      this.tradeInfo = res.data;
    })

    queryNewPrice().then(res => {
      this.tradeData = res.data;
      console.log(this.tradeData)
    })
    hideFullScreenLoading()
  },
  methods: {
    confirmBuy() {
      if (this.tradeForm.type === null) {
        this.$message.error('请选择碳资产类型');
      }
      buyCarbon(this.tradeForm).then(res => {

        this.dialogFormVisible = false;
        this.$message.success('碳资产购入成功');
      });
    },

    confirmSell() {
      if (this.tradeForm.type === null) {
        this.$message.error('请选择碳资产类型');
      }
      sellCarbon(this.tradeForm).then(res => {
        this.dialogFormVisible1 = false;
        this.$message.error('碳资产卖出成功');
      })
    },
    changeQuantity() {
      console.log(this.tradeForm.num)
      this.tradeForm.totalPrice = (parseFloat(this.tradeForm.num) * parseFloat(this.tradeForm.price)).toFixed(2);
    },
    showBuy(data, all) {
      this.dialogFormVisible = true;
      this.tradeForm.price = data.price;
      this.tradeForm.area = data.area;
    },
    showSell(data, all) {
      this.dialogFormVisible1 = true;
      this.tradeForm.price = data.price;
      this.tradeForm.area = data.area;
    },
    assertTrade(type) {
      this.assertDto.type = type;
      if (type === 1) {
        this.assertDto.num = this.quotaNum;
      } else if (type === 2) {
        this.assertDto.num = this.ccerNum;
      }
      carbonAssertTrade(this.assertDto).then(res => {
        if (res.code === 200) {
          this.$message.success('碳资产使用成功');
          queryCarbonAssert().then(res => {
            this.tradeInfo = res.data;
          })
          this.quotaNum = 0.00;
          this.ccerNum = 0.00;
          return;
        }
        this.$message.error('碳资产使用失败');
      })
    },
    confirmEdit() {
      this.ruleForm.beginDate = this.dateRange[0];
      this.ruleForm.endDate = this.dateRange[1];
      editTarget(this.ruleForm).then(res => {
        if (res.code === 200) {
          this.editTargetVisible = false;
          this.$message.success('编辑成功');
          this.loadData();
        }
      })
    },
    editTarget(item) {
      this.ruleForm.id = item.id;
      this.editTargetVisible = true;
      this.ruleForm.name = item.name;
      this.dateRange = [];
      this.dateRange.push(item.beginDate);
      this.dateRange.push(item.endDate);
      this.ruleForm.remark = item.remark;
      this.ruleForm.targetAmount = item.targetAmount;
      this.ruleForm.processList = JSON.parse(item.processList);
      this.ruleForm.stageList = JSON.parse(item.stageList);
      this.ruleForm.warningPercent = item.warningPercent;
    },
    clean() {
      this.form.assertType = '';
      this.form.tradeType = ''
      this.loadData();
    },
    searchTarget() {
      this.loadData();
    },
    async changeEnable(item) {
      if (item.enable === 0) {
        await enableTarget(item.id).then(res => {
          this.$message.success('启用成功');
        })
      } else {
        await unEnableTarget(item.id).then(res => {
          this.$message.success('禁用成功');
        })
      }
      await this.loadData();
    },
    loadData() {
      queryTradeList(this.form).then(res => {
        this.tableData = res.data.rows;
        this.total = res.data.total;
      })
    },
    handleClick(row) {
      this.detail.name = row.name;
      this.detail.id = row.id;
      this.detail.remark = row.remark;
      this.detail.targetAmount = row.targetAmount;
      this.detail.beginDate = row.beginDate;
      this.detail.endDate = row.endDate;
      this.activities = [{
        content: '开始日期',
        timestamp: row.beginDate,
        size: 'large',
        type: 'primary',
        color: '#c2e0c9'
      }, {
        content: '结束日期',
        timestamp: row.endDate,
        color: '#fa8888'
      }];
      this.detail.processList = JSON.parse(row.processList);
      this.detail.stageList = JSON.parse(row.stageList);
      this.dialogFormVisible = true;
      this.detail.enable = row.enable;
      this.detail.percentage = row.warningPercent;
      console.log(this.detail)
    },
    handleSizeChange(pageSize) {
      this.form.pageSize = pageSize
      this.loadData();
    },
    handleCurrentChange(pageNum) {
      this.form.pageNum = pageNum
      this.loadData();
    },
  },

}
</script>

<style scoped lang="scss">
.manage {
  margin: 10px;
}
</style>
